package com.example.myproject.controller;

import com.example.myproject.dto.CommonResponse;
import com.example.myproject.dto.message.ConversationDTO;
import com.example.myproject.dto.message.MessageDTO;
import com.example.myproject.security.JwtAuthenticationFilter;
import com.example.myproject.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @GetMapping("/conversations")
    public CommonResponse<List<ConversationDTO>> getUserConversations(
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal) {
        List<ConversationDTO> conversations = messageService.getUserConversations(principal.getId());
        return CommonResponse.success(conversations);
    }

    @GetMapping("/conversations/{conversationId}")
    public CommonResponse<List<MessageDTO>> getConversationMessages(
            @PathVariable Long conversationId) {
        List<MessageDTO> messages = messageService.getConversationMessages(conversationId);
        return CommonResponse.success(messages);
    }

    @PutMapping("/{messageId}/read")
    public CommonResponse<Void> markMessageAsRead(
            @PathVariable Long messageId,
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal) {
        messageService.markMessageAsReadByMessageId(messageId, principal.getId());
        return CommonResponse.success(null);
    }


    @MessageMapping("/send_message")
    public void handleMessage(@Payload MessageDTO messageDTO) {
        MessageDTO savedMessage = messageService.sendMessage(
                messageDTO.getFromUserId(),
                messageDTO.getToUserId(),
                messageDTO.getContent()
        );

        // 发送消息给发送者
        messagingTemplate.convertAndSendToUser(
                messageDTO.getFromUserId().toString(),
                "/queue/messages",
                savedMessage
        );

        // 发送消息给接收者
        messagingTemplate.convertAndSendToUser(
                messageDTO.getToUserId().toString(),
                "/queue/messages",
                savedMessage
        );
    }
}